package org.baicaixiaozhan.learn.guava.collect;

import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Maps;
import com.google.common.collect.Multiset;
import java.util.List;
import java.util.Map;

/**
 * DESC: {@link Multiset} 示例
 *
 * @author : baicaixiaozhan
 * @since : 2020-11-12
 */
public class MultisetDemo {

    public static void main(String[] args) {
        final String str = "1,2,3,4,,5,3,2,3,5, 7,3,2,1,1,7, ,5 ,6,6,6,6";

        // JDK
        countingInJava(str);

        // Guava
        countingInGuava(str);
    }

    public static void countingInJava(CharSequence input) {
        Preconditions.checkNotNull(input, "not null / ''");

        List<String> stringList = Splitter.on(",")
                .trimResults()
                .omitEmptyStrings()
                .splitToList(input);

        Map<String, Integer> countMaps = Maps.newHashMap();
        for (String str : stringList) {
            countMaps.merge(str, 1, Integer::sum);
        }
        System.out.println("=== counting in java ===");
        for (String key : countMaps.keySet()) {
            System.out.println("element : " + key + " count = " + countMaps.get(key));
        }

    }

    public static void countingInGuava(CharSequence input) {
        Preconditions.checkNotNull(input, "not null / ''");

        List<String> stringList = Splitter.on(",")
                .trimResults()
                .omitEmptyStrings()
                .splitToList(input);

        Multiset<String> multiset = HashMultiset.create(stringList);
        System.out.println("=== counting in Guava ===");
        for (String element : multiset.elementSet()) {
            System.out.println("element : " + element + " count = " + multiset.count(element));
        }
    }
}
